package com.example.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.example.exam.domain.AcademyDO;
import com.example.exam.domain.StudentDO;
import com.example.exam.service.IAcademyService;
import com.example.exam.service.IStudentService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@AllArgsConstructor
public class AcademyController {

    private final IAcademyService academyService;

    private final IStudentService studentService;

    @GetMapping({"/list", "/list.html"})
    public String listPage(Model model) {
        List<AcademyDO> listAcademyDO = academyService.list();
        model.addAttribute("listAcademyDO", listAcademyDO);
        return "list";
    }

    @GetMapping("/delete/{id}")
    @ResponseBody
    public String listPage(@PathVariable(name = "id") Long id) {
        long count = studentService.count(new LambdaQueryWrapper<StudentDO>()
                .eq(StudentDO::getMId, id));
        if (count > 0) {
            return "删除失败，请检查";
        }
        boolean b = academyService.removeById(id);
        return b ? "删除成功" : "删除失败，请检查";
    }
    @GetMapping("/edit/{id}")
    public String editPage(@PathVariable(name = "id")Long id,Model model) {
        AcademyDO byIdAcademyDO = academyService.getById(id);
        model.addAttribute("byIdAcademyDO", byIdAcademyDO);
        return "edit";
    }

    @PostMapping("/updateAcademy")
    @ResponseBody
    public String updateAcademy(AcademyDO academyDO) {
        boolean b = academyService.updateById(academyDO);
        return b ? "更新成功":"更新失败，请检查";
    }

    @GetMapping( "/add.html")
    public String addPage(Model model) {
        List<AcademyDO> listAcademyDO = academyService.list();
        model.addAttribute("listAcademyDO", listAcademyDO);
        return "add";
    }
    @PostMapping("/addAcademy")
    @ResponseBody
    public String addAcademy(AcademyDO academyDO) {
        boolean b = academyService.save(academyDO);
        return b ? "新增成功":"新增失败，请检查";
    }
}
